package controller;

import com.alibaba.fastjson.JSONObject;
import utils.UserManager;
import utils.MD5UsingMessageDigest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String email = req.getParameter("email");
        String password = req.getParameter("password");
        JSONObject resJson = new JSONObject();
        UserManager userManager = new UserManager();

        try {
            String passwordMD5 = MD5UsingMessageDigest.md5(password);
            boolean exist = userManager.userExists(email);
            if (exist) {
                if (userManager.userExists(email, passwordMD5)) {
                    resJson.put("status", "success");
                    resJson.put("message", "登录成功");
                } else {
                    resJson.put("status", "error");
                    resJson.put("error", "password"); // 设置错误类型为密码错误
                    resJson.put("message", "密码错误");
                }
            } else {
                resJson.put("status", "error");
                resJson.put("error", "email"); // 设置错误类型为邮箱错误
                resJson.put("message", "用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resJson.put("status", "error");
            resJson.put("message", "服务器错误");
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(resJson.toJSONString());
    }
}